﻿namespace SAD.DataCenter.InfoSources.SMS
{
    using System;
using System.Net;
    using SAD.Common.Models;
    using SAD.Common.Enums;
    using System.Text;

    public class SMSInfoSource : InfoSourceBase
    {
        private HttpListener m_HttpListener;
        private HttpListenerContext m_HttpListenerContext;
        private System.Threading.Thread m_HttpContextProcessThread;

        public SMSInfoSource()
        {
            m_HttpListener = new System.Net.HttpListener();

            m_HttpListener.Prefixes.Add("http://cnlamar.vicp.net/smsrecevice/");

            m_HttpContextProcessThread = new System.Threading.Thread(new System.Threading.ThreadStart(HttpContextProcess));
        }

        public override void Start()
        {
            m_HttpListener.Start();

            m_HttpContextProcessThread.Start();
        }

        public override void Stop()
        {
            m_HttpListener.Stop();
        }

        private void HttpContextProcess()
        {
            string responseString;
            byte[] responseBuffer;

            while (true)
            {
                m_HttpListenerContext = m_HttpListener.GetContext();

                //m_HttpListenerContext.Request.InputStream

                Encoding encoding = m_HttpListenerContext.Request.ContentEncoding;

                //读出请求内容
                string requestText = "";
                int requestBodyBufferSize = 1024;
                byte[] requestBodyBuffer = new byte[requestBodyBufferSize];
                while (true)
                {
                    int readCount = m_HttpListenerContext.Request.InputStream.Read(requestBodyBuffer, 0, requestBodyBufferSize);

                    requestText += encoding.GetString(requestBodyBuffer);

                    if (readCount < requestBodyBufferSize)
                    {
                        break;
                    }
                }

                //分析出请求参数
                System.Collections.Generic.Dictionary<string, string> requestParams = new System.Collections.Generic.Dictionary<string, string>();
                string[] requestParamStrings = requestText.Split('&');
                foreach (string paramString in requestParamStrings)
                {
                    if (paramString.IndexOf('=') > 0)
                    {
                        string paramKey = paramString.Substring(0, paramString.IndexOf('='));
                        string paramValue = paramString.Substring(paramString.IndexOf('=') + 1);

                        paramKey = System.Web.HttpUtility.UrlDecode(paramKey);
                        paramValue = System.Web.HttpUtility.UrlDecode(paramValue);

                        requestParams.Add(paramKey.ToLower(), paramValue);
                    }
                }

                if (!requestParams.ContainsKey("linkid") || !requestParams.ContainsKey("msg") || !requestParams.ContainsKey("phone"))
                {
                    //输出失败
                    responseString = string.Format("<HTML><BODY>api error {0}</BODY></HTML>", DateTime.Now);
                    responseBuffer = encoding.GetBytes(responseString);
                    m_HttpListenerContext.Response.ContentLength64 = responseBuffer.Length;
                    m_HttpListenerContext.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
                    m_HttpListenerContext.Response.OutputStream.Close();

                    continue;
                }

                int showNodeID, categoryID;

                string msg = requestParams["msg"];

                //去掉移动固定指令AE
                msg = msg.Substring(2);

                if (msg.IndexOf('#') > -1)
                {
                    string strShowNodeID = msg.Substring(0, msg.IndexOf('#'));
                    if (!int.TryParse(strShowNodeID, out showNodeID))
                    {
                        //失败,ShowNodeID格式错误
                    }
                    //未实现 - 数据库重检索ShowNodeID是否存在，不存在则错误

                    msg = msg.Substring(msg.IndexOf('#') + 1);

                    if (msg.IndexOf('#') > -1)
                    {
                        string strCategoryID = msg.Substring(0, msg.IndexOf('#'));
                        if (!int.TryParse(strCategoryID, out categoryID))
                        {
                            //失败,CategoryID格式错误
                        }
                    }
                    else
                    {
                        categoryID = 0;
                    }

                    msg = msg.Substring(msg.IndexOf('#') + 1);
                }
                else
                {
                    //输出失败
                    responseString = string.Format("<HTML><BODY>msg format error {0}</BODY></HTML>", DateTime.Now);
                    responseBuffer = encoding.GetBytes(responseString);
                    m_HttpListenerContext.Response.ContentLength64 = responseBuffer.Length;
                    m_HttpListenerContext.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
                    m_HttpListenerContext.Response.OutputStream.Close();

                    continue;
                }

                Info_ShowType showType = Info_ShowType.NormalText;
                string showData = msg;
                int sendUserID = 0;
                Info_SourceType sourceType = Info_SourceType.SMS;
                string sourceInfo = requestParams["phone"];//requestParams["linkid"];
                DateTime sendTime = DateTime.Now;
                Info_MacVerifyStatus info_MacVerifyStatus = Info_MacVerifyStatus.NoCheck;
                Info_ManVerifyStatus info_ManVerifyStatus = Info_ManVerifyStatus.NoCheck;
                Info_ShowStatus info_ShowStatus = Info_ShowStatus.No;

                Info_Data info = new Info_Data();
                info.InfoCategoryID = categoryID;
                info.ShowType = (byte)showType;
                info.ShowNodeID = showNodeID;
                info.ShowData = showData;
                info.SendUserID = sendUserID;
                info.SourceType  = (byte)sourceType;
                info.SourceInfo = sourceInfo;
                info.AddTime = sendTime;
                info.MacVerifyStatus = (byte)info_MacVerifyStatus;
                info.ManVerifyStatus = (byte)info_ManVerifyStatus;
                info.ShowStatus = (byte)info_ShowStatus;

                base.OwnerInfoSourceManager.NewInfoProcess(info);

                //输出成功
                responseString = string.Format("<HTML><BODY>1-{0}</BODY></HTML>", DateTime.Now);
                responseBuffer = encoding.GetBytes(responseString);
                m_HttpListenerContext.Response.ContentLength64 = responseBuffer.Length;
                m_HttpListenerContext.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
                m_HttpListenerContext.Response.OutputStream.Close();
            }
        }
    }
}